package com.xmtlxx.wms.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.bean.BeanUtil;
import com.xmtlxx.common.annotation.Log;
import com.xmtlxx.common.annotation.RepeatSubmit;
import com.xmtlxx.common.core.controller.BaseController;
import com.xmtlxx.common.core.domain.PageQuery;
import com.xmtlxx.common.core.domain.R;
import com.xmtlxx.common.core.domain.entity.SysDictData;
import com.xmtlxx.common.core.page.TableDataInfo;
import com.xmtlxx.common.core.validate.AddGroup;
import com.xmtlxx.common.core.validate.EditGroup;
import com.xmtlxx.common.core.validate.QueryGroup;
import com.xmtlxx.common.enums.BusinessType;
import com.xmtlxx.common.utils.poi.ExcelUtil;
import com.xmtlxx.wms.domain.bo.InventoryBo;
import com.xmtlxx.wms.domain.vo.DataVo;
import com.xmtlxx.wms.domain.vo.InventoryVo;
import com.xmtlxx.wms.service.IInventoryService;
import com.xmtlxx.system.service.ISysDictDataService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 库存Controller
 *
 * @author xmtlxx
 * @date 2022-08-15
 */
@Validated
@Api(value = "库存控制器", tags = {"库存管理"})
@RequiredArgsConstructor
@RestController
@RequestMapping("/wms/inventory")
public class InventoryController extends BaseController {

    private final IInventoryService iInventoryService;

    private final ISysDictDataService iSysDictDataService;

    /**
     * 返回一个初始化的对象到前端，方便进行动态渲染
     */
    @ApiOperation("用于返回一个初始化对象")
    @PostMapping("/initBean")
    R<InventoryVo> initBean(){
        InventoryVo vo = new InventoryVo();
        //可以对数据进行初始化
        return R.ok(vo);
    }

    /**
     * 查询库存列表
     */
    @ApiOperation("查询库存列表")
    @SaCheckPermission("wms:inventory:list")
    @GetMapping("/list")
    public TableDataInfo<InventoryVo> list(@Validated(QueryGroup.class) InventoryBo bo, PageQuery pageQuery) {
        return iInventoryService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出库存列表
     */
    @ApiOperation("导出库存列表")
    @SaCheckPermission("wms:inventory:export")
    @Log(title = "库存", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(@Validated InventoryBo bo, HttpServletResponse response) {
        List<InventoryVo> list = iInventoryService.queryList(bo);
        ExcelUtil.exportExcel(list, "库存", InventoryVo.class, response);
    }

    /**
     * 获取库存详细信息
     */
    @ApiOperation("获取库存详细信息")
    @SaCheckPermission("wms:inventory:query")
    @GetMapping("/{id}")
    public R<InventoryVo> getInfo(@ApiParam("主键")
                                     @NotNull(message = "主键不能为空")
                                     @PathVariable("id") String id) {
        return R.ok(iInventoryService.queryById(id));
    }

    /**
     * 新增库存
     */
    @ApiOperation("新增库存")
    @SaCheckPermission("wms:inventory:add")
    @Log(title = "库存", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody InventoryVo vo) {
        InventoryBo bo = new InventoryBo();
        BeanUtil.copyProperties(vo,bo);
        return toAjax(iInventoryService.insertByBo(bo) ? 1 : 0);
    }

    /**
     * 新增库存
     */
    @ApiOperation("新增库存")
    @SaCheckPermission("wms:inventory:add")
    @Log(title = "库存", businessType = BusinessType.INSERT)
    @PostMapping("/addStagingByInventory")
    public R<Void> addStagingByInventory(@Validated(AddGroup.class) @RequestBody InventoryVo vo) {
        InventoryBo bo = new InventoryBo();
        BeanUtil.copyProperties(vo,bo);
        return toAjax(iInventoryService.insertByStagingBo(bo) ? 1:0);
    }

    /**
     * 修改库存
     */
    @ApiOperation("修改库存")
    @SaCheckPermission("wms:inventory:edit")
    @Log(title = "库存", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody InventoryVo vo) {
        InventoryBo bo = new InventoryBo();
        BeanUtil.copyProperties(vo,bo);
        return toAjax(iInventoryService.updateByBo(bo) ? 1 : 0);
    }

    /**
     * 删除库存
     */
    @ApiOperation("删除库存")
    @SaCheckPermission("wms:inventory:remove")
    @Log(title = "库存", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@ApiParam("主键串")
                          @NotEmpty(message = "主键不能为空")
                          @PathVariable String[] ids) {
        return toAjax(iInventoryService.deleteWithValidByIds(Arrays.asList(ids), true) ? 1 : 0);
    }

    /**
     * 统计区县数据
     */
    @ApiOperation("统计区县数据")
    @GetMapping("/statisticsTask")
    public R<Map<String,Object>> statisticsTask() {
        Map<String,Object> data = new HashMap<>();
        List<InventoryVo> dataVos = iInventoryService.queryInventoryByList();

        SysDictData dictData = new SysDictData();
        dictData.setDictType("wms_put_task_area");
        List<SysDictData> dictDataList = iSysDictDataService.selectDictDataList(dictData);

        //taskVo转dataVo
        List<DataVo> taskData = dataVos.stream().map(item->{
            DataVo dataVo = new DataVo();
            dataVo.setRegion(item.getRegion());
            dataVo.setRegionName(item.getRegionName());
            dataVo.setTotals(item.getTotals());
            return  dataVo;
        }).collect(Collectors.toList());

        List<DataVo> dictDataVos = dictDataList.stream().map(item->{
            DataVo dataVo = new DataVo();
            dataVo.setRegion(item.getDictValue());
            dataVo.setRegionName(item.getDictLabel());
            dataVo.setTotals(0l);
            return dataVo;
        }).collect(Collectors.toList());

        //taskData 合并到 dictDataVos
        List<DataVo> result = dictDataVos.stream().map(d->{
            taskData.stream().filter(d2-> Objects.equals(d.getRegion(),d2.getRegion())).forEach(d2->{
                BeanUtil.copyProperties(d2,d);
            });
            return d;
        }).collect(Collectors.toList());
        result = result.stream().filter(item->!item.getRegion().equals("QB")).collect(Collectors.toList());
        data.put("result",result);

        return R.ok(data);
    }
}
